'use strict';

angular.module('xuexibangApp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ui.router'
  ])
  .config(function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
    $urlRouterProvider
      .otherwise('/');
    $locationProvider.html5Mode(true);
    $httpProvider.interceptors.push('authInterceptor');
    $httpProvider.interceptors.push('httpRequestInterceptorCacheBuster');
  })
  .factory('authInterceptor', function($rootScope, $q, $cookieStore, $location) {
    return {
      // Add authorization token to headers
      request: function(config) {
        config.headers = config.headers || {};
        if ($cookieStore.get('token')) {
          config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
        }
        return config;
      },

      // Intercept 401s and redirect you to login
      responseError: function(response) {
        if (response.status === 401) {
          $location.path('/login');
          // remove any stale tokens
          $cookieStore.remove('token');
          return $q.reject(response);
        } else {
          return $q.reject(response);
        }
      }
    };
  })
  .directive('ngNext', function() {
    return function(scope, element, attrs) {
      element.bind("keydown keypress", function(event) {
        if (event.which === 13 || event.which === 38 || event.which === 40) {
          scope.$apply(function() {
            scope.$eval(attrs.ngNext, {
              'event': event
            });
          });
          event.preventDefault();
        }
      });
    };
  })
  .factory('httpRequestInterceptorCacheBuster', function() {
    return {
      request: function(config) {
        //console.log(config.url,config.url.indexOf('app/'));
        if (config.method == 'GET' && (config.url.indexOf('api/')>-1 || config.url.indexOf('auth/')>-1)){//模板编译进了js，加入参数，恢复失败
          var separator = config.url.indexOf('?') === -1 ? '?' : '&';
          config.url = config.url + separator + 'cacheSlayer=' + new Date().getTime();
        }
        return config;
      }
    };
  })
  .run(function($rootScope, $location, Auth) {
    // Redirect to login if route requires auth and you're not logged in
    $rootScope.$on('$stateChangeStart', function(event, next) {
      Auth.isLoggedInAsync(function(loggedIn) {
        if (next.authenticate && !loggedIn) {
          $location.path('/login');
        }
      });
    });
  });
